package pdfmerge;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.exceptions.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFMergerUtility;

public class PDFMergeDemo {

	/**
	 * @param args
	 */
	private static String[] getFiles(String folder) throws IOException {
		File _folder = new File(folder);
		String[] filesInFolder;

		if (_folder.isDirectory()) {
			filesInFolder = _folder.list();
			return filesInFolder;
		} else {
			throw new IOException("Path is not a directory");
		}
	}

	public static void main(String[] args) throws Exception {

		PDFMergerUtility mergePdf = new PDFMergerUtility();

		String folder = "E:/ZSLP/pdf/RELEVE_PDF_20150630";//"F:/Workspace/PDFboxDemo/pdffile";
		String destinationFileName = "mergedTest.pdf";

		String[] filesInFolder = getFiles(folder);
		

		for (int i = 0; i < filesInFolder.length; i++) {
			//获取PDF文件总页数
			/*PDDocument pdd = PDDocument.load(folder + File.separator + filesInFolder[i]);
			System.out.println(filesInFolder[i]+"页数="+pdd.getNumberOfPages());
			pdd.close();*/
			/*File file = new File(folder + File.separator + filesInFolder[i]);
			InputStream in = new FileInputStream(file);*/
			mergePdf.addSource(folder + File.separator + filesInFolder[i]);
		}

		mergePdf.setDestinationFileName(folder + File.separator
				+ destinationFileName);
		mergePdf.mergeDocuments();

		System.out.print("pdf merge done");

	}
	
	public static void parseDocument(InputStream input) throws IOException {  
       // PDDocument document = PDDocument.load(input); 
        Field f;
		try {
			f = input.getClass().getDeclaredField("encrypted");
			f.setAccessible(true);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }  

}